package com.hotel.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hotel.common.lang.Result;
import com.hotel.entity.*;
import com.hotel.mapper.EnterMapper;
import com.hotel.service.EnterService;
import com.hotel.service.HouseService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2020-10-19
 */
@RestController
@RequestMapping("/enter")
public class EnterController {
    @Autowired
    EnterService enterService;
    @Autowired
    HouseService houseService;
    @Autowired
    EnterMapper enterMapper;

    //展示每层楼的房间及其状态
    @RequestMapping("/checklist")
    public Result checklist(House house) {
        house.setFloorId(1);
        QueryWrapper<House> houseQueryWrapper = new QueryWrapper<House>().eq("floor_id", house.getFloorId());
        List<House> houseList = houseService.list(houseQueryWrapper);
        List<String> houseId = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> amounts = new ArrayList<>();
        List<BigDecimal> prices = new ArrayList<>();
        List<Integer> houseStates = new ArrayList<>();
        List<Integer> enterStates = new ArrayList<>();
        System.out.println("结果集: " + houseList);
        for (House h : houseList
        ) {
            ids.add(h.getId());
            names.add(h.getName());
            amounts.add(h.getAmount());
            prices.add(h.getPrice());
            houseStates.add(h.getState());
        }
        QueryWrapper<Enter> enterQueryWrapper = new QueryWrapper<Enter>().in("house_id", ids);
        List<Enter> enterList = enterService.list(enterQueryWrapper);
//        for (House h:houseList
//             ) {
//            System.out.println(h);
//        }
//        System.out.println("a");
//        for (Enter e:enterList
//        ) {
//            System.out.println("b");
//            System.out.println(e);
//        }
        for (Enter e : enterList
        ) {
            enterStates.add(e.getState());
        }
        return Result.succ(MapUtil.builder()
                .put("id", ids)
                .put("name", names)
                .put("amount", amounts)
                .put("price", prices)
                .put("houseState", houseStates)
                .put("enterState", enterStates)
                .map());
    }


    //入住操作,修改 state ,设置start_time和end_time_estimate以及收取押金
    @RequestMapping("/enteractive")
    public Result enteractive(House house, User user, List<Integer> customerIdList, int day) {
//        House house = new House();
//        house.setName("a1001");
//        house.setPrice(new BigDecimal(100));
//        int day = 3;
//        List<Integer> customerIdList = new ArrayList<>();
//        customerIdList.add(101);
//        customerIdList.add(102);
//        User user = new User();
//        user.setId(001);

        Date utilDate1 = new Date();
//        System.out.println("utilDate1 : " + utilDate1);

        Timestamp sqlDate1 = new Timestamp(utilDate1.getTime());
//        System.out.println("sqlDate1 : " + sqlDate1);

        Date utilDate2 = new Date(utilDate1.getTime() + day * 24 * 60 * 60 * 1000);
//        System.out.println("utilDate2"+utilDate2);
        Timestamp sqlDate2 = new Timestamp(utilDate2.getTime());
//        System.out.println("sqlDate2"+sqlDate2);

        int min = 1280000000;
        String str = "";
        for (int i : customerIdList
        ) {
            if (str == "") {
                str = i + "";
            } else {
                str += "|" + i;
            }
//            System.out.println(str);
            if (i <= min) {
                min = i;
            }
        }

        UpdateWrapper enterupdatewrapper = new UpdateWrapper();
        enterupdatewrapper.eq("house_id", house.getName());
        enterupdatewrapper.set("state", 2);
        enterupdatewrapper.set("start_time", sqlDate1);
        enterupdatewrapper.set("end_time_estimate", sqlDate2);
        enterupdatewrapper.set("customer_info", min);
        enterupdatewrapper.set("customer_info", str);
        enterupdatewrapper.set("deposit", house.getPrice().multiply(new BigDecimal(2)));
        enterupdatewrapper.set("user_id", user.getId());
        enterService.update(null, enterupdatewrapper);
        return Result.succ("操作成功");
    }

    //更新房间缴费记录
    @RequestMapping("/payrecords")
    public Result payrecords(Fee fee) {

//        Fee fee = new Fee();
//        fee.setId(123);
//        fee.setEnterId(1);
//        fee.setMoney(120);


        //根据enterID去找入住的记录
        Enter enter = new Enter();
        enter = enterService.getById(fee.getEnterId());
        int feeid = 0;
        System.out.println(fee);
        System.out.println(enter);
        //获取系统时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());

        //编辑新的单号
        String newrecord = "|" + fee.getId() + ":" + date;
        System.out.println("aaaaaaaaaaa");
        //取出原始单号字符串
        String oldrecord = enter.getFeeInfo();
        System.out.println("-----------" + oldrecord);
        String feeInfo = oldrecord + newrecord;
        System.out.println("bbbbbbbbbbbb");

        if (oldrecord.contains(fee.getId() + "")) {
            //如果这个单号已经存在则只加总缴费金额
            UpdateWrapper<Enter> enterUpdateWrapper = new UpdateWrapper<Enter>();
            enterUpdateWrapper.eq("id", fee.getEnterId());
            enterUpdateWrapper.in("state", 1, 2, 3);
            enterUpdateWrapper.set("fee_total", enter.getFeeTotal() + fee.getMoney());
            enterService.update(null, enterUpdateWrapper);
        }
        if (oldrecord == null || oldrecord.equals("") || !oldrecord.contains(fee.getId() + "")) {
            //如果字段中还不存在单号
            if (oldrecord == null || oldrecord.equals("")) {
                feeInfo = fee.getId() + ":" + date;
            }
            //如果这个单号不存在或不存在任何单号则既要计算总金额又要把单号和时间加在后面
            UpdateWrapper<Enter> enterUpdateWrapper = new UpdateWrapper<Enter>();
            enterUpdateWrapper.eq("id", fee.getEnterId());
            enterUpdateWrapper.in("state", 1, 2, 3);
            enterUpdateWrapper.set("fee_total", enter.getFeeTotal() + fee.getMoney());
            enterUpdateWrapper.set("fee_info", feeInfo);
            enterService.update(null, enterUpdateWrapper);
        }
        return Result.succ("操作成功");
    }


    //展示缴费记录
    @RequestMapping("/showrecords")
    public Result showrecords(Enter enter) {

//        Enter enter = new Enter();
//        enter.setId(1);

        enter = enterService.getById(enter.getId());
        String feerecod = enter.getFeeInfo();
//        String record[] = new String[2];
        Map<Integer, String> fee_map = new HashMap<>();
        //如果没有记录
        if ("".equals(feerecod) || feerecod == null) {
            return Result.succ(null);
        } else {
            //如果有多条记录
            if (feerecod.contains("|")) {
                String records[] = feerecod.split("\\|");
                for (int i = 0; i < records.length; i++) {
                    String record[] = records[i].split("-");


                    fee_map.put(Integer.valueOf(record[0]), record[1]);
                }
            } else {
                //如果只有一条记录
                String record[] = feerecod.split(":");
                fee_map.put(Integer.valueOf(record[0]), record[1]);
            }
            return Result.succ(fee_map);
        }
    }

    /**
     * 功能描述: <br>
     * 〈〉 显示预订的订单信息
     *
     * @Param: [enter]
     * @Return: com.hotel.common.lang.Result
     * @Author: Administrator
     * @Date: 2020/11/1 19:51
     */
    @RequestMapping("/showOrder")
    public Result showOrder() {
//        当状态为1时表示房间为已订购状态
        QueryWrapper<Enter> EnterQueryWrapper = new QueryWrapper<Enter>().eq("state", 1);
        List<Enter> EnterList = enterService.list(EnterQueryWrapper);
        System.err.println(EnterList);
        return Result.succ(EnterList);
    }

    /**
     * 功能描述: <br>
     * 〈〉添加订购信息
     *
     * @Param: [house]
     * @Return: java.lang.String
     * @Author: Administrator
     * @Date: 2020/11/1 21:34
     */
    @RequestMapping("/addEnter")
    public Result addHouse(@RequestBody Enter enter) {
        System.out.println(enter);
//        设置为预订的状态
        enter.setState(1);
        int i = enterMapper.insert(enter);
        String str = i > 0 ? "success" : "error";
        HashMap<String,String> map = new HashMap<>();
        map.put("info",str);
        return Result.succ(map);
    }
    /**
     * 功能描述: <br>
     * 〈〉删除订单操作
     * @Param: [id]
     * @Return: void
     * @Author: Administrator
     * @Date: 2020/11/1 22:22
     */
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        enterMapper.deleteById(id);
    }
}
